const OSS = require("ali-oss");
const fs = require("fs");
const path = require("path");
const { pathToAliPrefix, aliPrefixesName, aliObjectsName } = require('../utils/utils')
const chalk = require('chalk')

const fetchList = async ({ client, cToken, prefix, delimiter }) => {
    const objects = []
    const prefixes = []
    const nowResult = await client.listV2({
        prefix,
        delimiter,
        'continuation-token': cToken,
        'max-keys': 100
    })
    objects.push(...(nowResult?.objects || []))
    prefixes.push(...(nowResult?.prefixes || []))
    if (nowResult?.nextContinuationToken) {
        const { objects: restObjects, prefixes: restPrefixes } = await fetchList({
            client,
            prefix,
            delimiter,
            cToken: nowResult?.nextContinuationToken,
        })
        objects.push(...(restObjects || []))
        prefixes.push(...(restPrefixes || []))
    }
    return {
        objects,
        prefixes
    }
}

module.exports = async function ({ config, rootName = "/", type, max }) {
    const ossConfig = config || this.getOssConfig()
    const prefix = pathToAliPrefix(rootName)
    const client = new OSS(ossConfig);
    const { objects, prefixes } = await fetchList({
        client,
        cToken: "",
        prefix,
        delimiter: '/',
    })
    const tPrefixesName = aliPrefixesName(prefixes, prefix)
    const tObjectsName = aliObjectsName(objects, prefix)
    if (type === 'dir') {
        console.log(chalk.blue("目录:"));
        console.log(tPrefixesName.slice(0,max||100))
    } else if (type === 'file') {
        console.log(chalk.blue("文件:"))
        console.log(tObjectsName.slice(0,max||100))
    } else {
        console.log(chalk.blue("目录:"));
        console.log(tPrefixesName.slice(0,max||100))
        console.log(chalk.blue("文件:"))
        console.log(tObjectsName.slice(0,max||100))
    }
    const dirs = tPrefixesName.map(item => ({
        name: item,
        typeCn: '目录'
    }))
    const files = tObjectsName.map(item => ({
        name: item,
        typeCn: '文件'
    }))
    fs.writeFileSync(path.resolve('list.json'), JSON.stringify(dirs.concat(files), '', '\t'))
}